const fs = require('fs');
const http = require('http');
const path = require('path');
// const chalk = require("chalk")
const port = 8888;
const directoryName = './';

const types = {
  html: 'text/html',
  css: 'text/css',
  js: 'application/javascript',
  png: 'image/png',
  jpg: 'image/jpeg',
  jpeg: 'image/jpeg',
  gif: 'image/gif',
  json: 'application/json',
  xml: 'application/xml',
};

const root = path.normalize(path.resolve(directoryName));


const server = http.createServer((req, res) => {
  req.url = req.url.split("?")[0]
  const extension = path.extname(req.url).slice(1);
  const type = extension ? types[extension] : types.html;
  const supportedExtension = Boolean(type);
  if (!supportedExtension) {
    res.writeHead(404, { 'Content-Type': 'text/html' });
    res.end('404: File not found');
    return;
  }

  let fileName = req.url;
  if (req.url === '/') {
    let fileArray = []
    let count = 0
    fs.readdir(directoryName, "utf8", (err, data) => {
      data.forEach((item, i) => {
        ((i) => {
          fs.stat(directoryName + '/' + item, (file_err, file_data) => {
            count++
            // 说明是一个文件夹
            try {
              if (file_data.isDirectory()) {
                fileArray.push({
                  type: "folder",
                  time: file_data.ctime,
                  url: `http://localhost:${port}/${item}`,
                  name: item
                })
              } else {
                fileArray.push({
                  type: "folder",
                  time: file_data.ctime,
                  url: `http://localhost:${port}/${item}`,
                  name: item
                })
              }
            } catch (err) {
              err
            }
            if (count == data.length) {
              let string = `<!DOCTYPE html>
              <html lang="">
                <head>
                  <meta charset="utf-8">
                  <meta http-equiv="X-UA-Compatible" content="IE=edge">
                  <meta name="viewport" content="width=device-width,initial-scale=1.0">
                  <title>列表</title>
                </head>
                <body>
                <h1>列表</h1>
              `
              fileArray.forEach(umd => {
                string += `<h2>${umd.name}</h2><a href="${umd.url}" target="_blank">${umd.url}</a><br />`
              })
              string += `</body></html>`
              res.end(string)
            }
          })
        })(i)
      })
    })
  } else {
    if (!extension) {
      try {
        fs.accessSync(path.join(root, req.url + '.html'), fs.constants.F_OK);
        fileName = req.url + '.html';
      } catch (e) {
        fileName = path.join(req.url, 'index.html');
      }
    }
    const filePath = path.join(root, fileName);
    const isPathUnderRoot = path
      .normalize(path.resolve(filePath))
      .startsWith(root);

    if (!isPathUnderRoot) {
      res.writeHead(404, { 'Content-Type': 'text/html' });
      res.end('404: File not found');
      return;
    }
    fs.readFile(filePath, (err, data) => {
      if (err) {
        res.writeHead(404, { 'Content-Type': 'text/html' });
        res.end('404: File not found');
      } else {
        res.writeHead(200, {
          "Access-Control-Allow-Origin": "*",
          'Content-Type': type
        });
        res.end(data);
      }
    });
  }

});

server.listen(port, () => {
  // eslint-disable-next-line no-console
  console.log('列表:', `http://localhost:${port}`);
});